package com.nnfe.fyd.feature.login;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.nnfe.fyd.R;
import com.nnfe.fyd.ShareKey;
import com.nnfe.fyd.base.ActionBarFragment;
import com.nnfe.fyd.bean.ChannelBean;
import com.nnfe.fyd.bean.HttpResult;
import com.nnfe.fyd.bean.SaveChannelBean;
import com.nnfe.fyd.bean.registerAndLogin.LoginBean;
import com.nnfe.fyd.http.CallbackImpl;
import com.nnfe.fyd.utils.DialogUtil;
import com.nnfe.fyd.utils.FragmentUtil;
import com.nnfe.fyd.utils.SharePrefUtil;
import com.nnfe.fyd.utils.StringUtil;
import com.nnfe.fyd.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * ----------------------------------
 * Created by xyd on 2017/3/15.
 * <p/>
 * 描  述：
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class LoginFragment extends ActionBarFragment {
    @Bind(R.id.body)
    CoordinatorLayout coordinatorLayout;
    @Bind(R.id.et_phone_num)
    EditText etPhoneNum;
    @Bind(R.id.et_psd)
    EditText etPsd;
    @Bind(R.id.btn_next)
    Button btnNext;
    private String phoneNum;
    private String passWord;
    private LoginBean loginData;

    @Override
    public Object getTitleString() {
        return "登录";
    }


    @Override
    public int getContentView() {
        return R.layout.fragment_login;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }

    @Override
    protected void initView() {

        etPhoneNum.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (isDetached() && !hasFocus) {
                    if (!StringUtil.isMobile(etPhoneNum.getText().toString().trim())) {
                        ToastUtil.showToast("输入手机号码格式不正确！");
                    }
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.btn_next, R.id.tv_forget_psd, R.id.tv_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_next:
                if (checkCanLogin()) {
                    login();
                }
                break;
            case R.id.tv_forget_psd:
                FragmentUtil.replaceWithAddToBack(mContext, new ResetPwdFragment());
                break;
            case R.id.tv_register:
                FragmentUtil.replaceWithAddToBack(mContext, new RegisterFragment());
                break;
        }
    }

    private void login() {
        DialogUtil.showLoadingDialog(mContext, "登录中...");
        Call<HttpResult<LoginBean>> call = service.doLogin(phoneNum, passWord);
        call.enqueue(new CallbackImpl<LoginBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<LoginBean>> call, Response<HttpResult<LoginBean>> response) {
                if (response.body().getStatus() == 0) {
                    loginData = response.body().getData();
                    SharePrefUtil.saveString(mContext, ShareKey.UserId, loginData.userInfo.id);
                    if (loginData.channel == null) {
                        getChannelList();
                    } else {
                        saveData(loginData);
                        mContext.finish();
                    }
                }
            }

            @Override
            protected void onRequestFinish() {
                DialogUtil.dismissLoadingDialog(mContext);
            }
        });
    }

    /**
     * 保存个人信息
     *
     * @param data
     */
    private void saveData(LoginBean data) {

        SharePrefUtil.saveBoolean(mContext, ShareKey.isLogin, true);
        SharePrefUtil.saveString(mContext, ShareKey.UserId, data.userInfo.id);
        SharePrefUtil.saveString(mContext, ShareKey.Mobile, data.userInfo.mobile);
        SharePrefUtil.saveString(mContext, ShareKey.Name, data.userInfo.name);
        SharePrefUtil.saveString(mContext, ShareKey.Token, data.token);
        if (data.channel != null && data.channel.channel != null) {
            SharePrefUtil.saveString(mContext, ShareKey.ChannelName, data.channel.channel.channelName);
        }

    }

    private void getChannelList() {
        Call<HttpResult<List<ChannelBean>>> call = service.getChannel();
        call.enqueue(new CallbackImpl<List<ChannelBean>>() {
            @Override
            public void responseSuccess(Call<HttpResult<List<ChannelBean>>> call, Response<HttpResult<List<ChannelBean>>> response) {
                if (response.isSuccessful()) {
                    if (response.body().data != null && response.body().data.size() > 0) {
                        ArrayList<String> channelNameList = new ArrayList<String>();
                        final ArrayList<String> channelIdList = new ArrayList<String>();
                        for (int i = 0; i < response.body().data.size(); i++) {
                            channelNameList.add(response.body().data.get(i).channelName);
                            channelIdList.add(response.body().data.get(i).id);
                        }
                        DialogUtil.showListDialog(mContext, "注册渠道", channelNameList, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                saveChannel(channelIdList.get(which));
                            }
                        });

                    }else {
                        ToastUtil.showToast("无可用渠道，请稍后再试...");
                    }
                }
            }
        });
    }

    private void saveChannel(String channelId) {
        DialogUtil.showLoadingDialog(mContext, "保存中...");
        Call<HttpResult<SaveChannelBean>> call = service.saveChannel(SharePrefUtil.getString(mContext, ShareKey.UserId, ""), null, channelId);
        call.enqueue(new CallbackImpl<SaveChannelBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<SaveChannelBean>> call, Response<HttpResult<SaveChannelBean>> response) {
                if (response.isSuccessful()) {
                    //ToastUtil.showToast("保存成功");
                    saveData(loginData);
                    SharePrefUtil.saveString(mContext, ShareKey.ChannelName, response.body().data.channelName);
                    mContext.finish();
                }
            }

            @Override
            protected void onRequestFinish() {
                DialogUtil.dismissLoadingDialog(mContext);
            }
        });

    }

    private boolean checkCanLogin() {
        phoneNum = etPhoneNum.getText().toString().trim();
        passWord = etPsd.getText().toString().trim();

        if (!StringUtil.isMobile(phoneNum)) {
            ToastUtil.showToast("输入手机号码格式不正确！");
            return false;
        }

//        if (passWord.length() < 6 || passWord.length() > 16) {
        if (passWord.length() <= 0) {

            ToastUtil.showToast("输入密码格式不正确！");
            return false;
        }


        return true;

    }

}
